package com.ks.phone.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.ks.phone.provider.ContextGlobal;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class FileUtils {
    public static String getRecordPath() {
        // 获取通话录音的URI
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        // 查询通话录音的路径
        Cursor cursor = ContextGlobal.get().getContext().getContentResolver()
                .query(uri, null, null, null, null);

        // 返回通话录音的路径
        if (cursor != null && cursor.moveToFirst()) {
            int pathIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
            String path = cursor.getString(pathIndex);
            int i = path.lastIndexOf("/");
            return path.substring(0, i);
        }
        return "";
    }

    public static ArrayList<String> getCallRecordingPaths(Context context) {
        ArrayList<String> paths = new ArrayList<>();
        Cursor cursor = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            String[] projection = {MediaStore.Audio.Media.DATA};
            cursor = contentResolver.query(uri, projection, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    // 这里可以添加判断条件，过滤出通话录音文件，例如通过文件名或者其他属性
                    paths.add(path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return paths;
    }

    public static AtomicBoolean isConnected = new AtomicBoolean(true);

    public static File searchFiles(File directory, String phone) {
        Log.d("zhxk", "searchFiles: directory = " + directory.getAbsolutePath()
                + " phone = " + phone);
        if (phone == null) {
            return null;
        }
        File targetFile = null;

        if (directory.isDirectory()) {
            Log.d("zhxk", "searchFiles: 111");
            File[] files = directory.listFiles();
            Log.d("zhxk", "searchFiles: 222");
            if (files != null) {
                Log.d("zhxk", "searchFiles: 333 files.length = " + files.length);
                if (files.length > 0) {
                    long lastModifiedTime = 0;
                    for (File file : files) {
                        if (file.getName().contains(phone) && file.lastModified() > lastModifiedTime) {
                            lastModifiedTime = file.lastModified();
                            targetFile = file;
                            Log.d("zhxk", "searchFiles: 444 file.getName() = " + file.getName()
                                    + " file.lastModifiedTime = " + lastModifiedTime);
                        }
                    }
                    // 如果录音的时间-当前系统时间 < 1分钟，则判定为录音有效
                    Log.d("zhxk", "searchFiles: lastModifiedTime = " + lastModifiedTime);
                    Log.d("zhxk", "searchFiles: System.currentTimeMillis() = " + System.currentTimeMillis());
                    Log.d("zhxk", "searchFiles: Math.abs(System.currentTimeMillis() - lastModifiedTime) = "
                            + Math.abs(System.currentTimeMillis() - lastModifiedTime));
                    if (lastModifiedTime > 0 && Math.abs(System.currentTimeMillis() - lastModifiedTime) < 60 * 1000) {
                        isConnected.set(true);
                        return targetFile;
                    } else {
                        isConnected.set(false);
                        return null;
                    }
                }
            }
        }
        Log.d("zhxk", "searchFiles: 555");
        return null;
    }

    /**
     * desc: 获取文件时长，返回单位ms
     * author: 康少
     * time: 2024/4/29
     */
    public static int getMp3Duration(File file) {
        if (!isMP3File(file)) {
            Log.e("zhxk", "录音文件不是mp3文件");
            return 0;
        }

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int duration = 0;
        try {
            retriever.setDataSource(file.getAbsolutePath());
            String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            duration = Integer.parseInt(durationStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return duration;
    }

    private static boolean isMP3File(File file) {
        if (file == null || !file.exists()) {
            return false;
        }

        String fileName = file.getName();
        return fileName.toLowerCase().endsWith(".mp3");
    }

    /**
     * 保存文本到本地文件
     *
     * @param content    文本内容
     * @param targetFile 目标文件
     * @param append     true代表接上文件内容；false代表从头开始
     * @return 是否保存成功
     */
    public static boolean saveContentToFile(String content, File targetFile, boolean append) {
        try {
            // 创建 FileWriter 对象，append：true代表接上文件内容；false代表从头开始
            FileWriter fileWriter = new FileWriter(targetFile, append);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            // 写入文本内容
            bufferedWriter.write(content);
            bufferedWriter.newLine();
            // 关闭 FileWriter
            bufferedWriter.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 清空文件内容
     *
     * @param targetFile 目标文件
     * @return 返回是否清除成功
     */
    public static boolean cleanFileContent(File targetFile) {
        // 检查外部存储是否可用
        if (!isExternalStorageWritable()) {
            return false;
        }
        try {
            FileWriter fileWriter = new FileWriter(targetFile);
            fileWriter.write(""); // 将文件内容设置为空字符串
            fileWriter.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * desc: 外部存储是否可用
     * author: 康少
     * time: 2023/11/22
     */
    private static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }
}
